package com.hnhs.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.hnhs.info.ImgInfo;
import com.hnhs.info.UploadInfo;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/upload")
public class UploadController {
    //提取路径
    private static String filePath="D:/software/nginx-1.21.4/html/";
    //上传的文件类型
    private static List<String> imgExts = CollUtil.newArrayList("jpg","png"
    ,"jpeg","gif");

    @PostMapping
    public String upload(@RequestBody UploadInfo uploadInfo){
        String name = uploadInfo.getName();
        String base64 = uploadInfo.getBase64();
        // 获取base64的数据 然后截取
        String[] base64s = StrUtil.splitToArray(base64, "base64,");

        //把字符串数组转换为 字节数组
        byte[] bytes = Base64.decode(base64s[1]);
        // 雪花算法  数字+ _+名字 str 字符串
        name= IdUtil.getSnowflakeNextIdStr()+"_"+name;
        String extimg = FileUtil.getSuffix(name);
        //文件夹
        String tempFolder ="images/";
        if(!imgExts.contains(extimg)){
            tempFolder=extimg+"/";
        }

        FileUtil.writeBytes(bytes,filePath+tempFolder+name);
        return "http://www.hphs.com/"+tempFolder+name;
    }

    @GetMapping
    public List<ImgInfo> getImgList(){
        //获取指定的目录
        List<String> fileNames = FileUtil.listFileNames("D:/software/nginx-1.21.4/html/images/");
        //获取 里面数据 需要把所有文件转换为 list集合
        // stream 可以获取map类型数据f
        List<ImgInfo> collect = fileNames.stream().map(
                item -> {
                    return new ImgInfo(item, "http://www.hphs.com/images/" + item);
                }
        ).collect(Collectors.toList());

        return collect;

    }
}
